package org.liufumore.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * 工具包用于获取连接
 */
public class DBUtils {
    /**
     * 获取会话
     * @return SqlSession会话对象
     */
    public SqlSession getSession(){
        //mybatis资源的配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        //捕获异常
        try {
            //通过文件流获取配置信息
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //通过会话工厂获取会话对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //自动提交事务，就传递参数true
        SqlSession session = sqlSessionFactory.openSession();
        return session;
    }
}
